from flask import Flask
from flask import request
import requests as req


app = Flask(__name__)

appid = "wx9fd4c1726e80aff9"
appsecret = "8b350ac48a2de74e90e6a1de0e9c25a4"
# code encryptedData iv 由客户端反过来
wxcode = "" 
encrypteddata=""
iv=""

# 服务器端根据code 获取sessionkey 和openid
openid=""
sessionkey=""

'''
请求 获取sessionkey 和openid
'''
def code2session():
    global openid
    global sessionkey

    url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code".format(appid,appsecret,wxcode)
    res = req.get(url)
    dd = res.json()
    print("*******************code2session********************")
    if dd.get("errcode") == None:
        global sessionkey
        global openid
        print("***********OK************")
        sessionkey = dd['session_key']
        openid = dd['openid']
        return decode_wx_phone()
    else:
        print("***********错误************")
        print(dd)
        return {"code":500,"msg":dd}


'''
解析手机号
'''
def decode_wx_phone():
    from wx_encode import WXDeCode
    pc = WXDeCode(appid, sessionkey)
    mobile_obj = pc.decrypt(encrypteddata, iv)
    mobile = mobile_obj['phoneNumber']
    return {"data":{
        "openid":openid,
        "token":"szw",
        "tokenkey":"szwkey"
    },"code":200,"msg":"login ok"}

'''
微信登录 并获得手机号
'''
@app.post('/client/wxMinLogin')
def wxMinLogin():
    global wxcode
    global encrypteddata
    global iv
    data = request.json;
    wxcode = data["code"]
    encrypteddata = data["encryptedData"]
    iv = data["iv"]
    return code2session()


'''
支付回调
'''
@app.get('/oayresult')
def payresult():
    print(request.json)


'''
支付操作
'''
@app.post('/api/admin/seckill/order/payOrder')
def apipay():
    from wx_pay import WX_PayToolUtil
    data = request.json
    paytool = WX_PayToolUtil(APP_ID=appid,MCH_ID="123123",API_KEY="111111111111",NOTIFY_URL="http://127.0.0.1:5000/payresult")
    return paytool.getPayUrl("dd2021456489797",openid,0.01)










if __name__ == "__main__":
    app.run(debug=True)

